package com.htz.java250805_library.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.htz.java250805_library.constants.Constants;
import com.htz.java250805_library.entity.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行preHandle方法");
        response.setContentType("application/json;charset=utf-8");
        //response.setCharacterEncoding("utf-8");
        //表示放行  true  拦截 false
        //判断用户是否登录
        HttpSession session = request.getSession(false);

        if (session != null && StringUtils.hasLength((String) session.getAttribute(Constants.SESSION_USERNAME))){
            //说明用户登录了
            log.info("用户已登录");
            return true;
            //return Result.unlogin();
        }
        log.info("用户未登录");
        //说明未登录
        Result result = Result.unlogin();
        response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
        response.setStatus(401); //http 状态码
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("执行postHandle 方法");
    }
}












































